#!/bin/bash

helpFunction()
{
    echo ""
    # set color to green
    echo -e '\e[1;32m '
    echo "Usage: $0 "
    echo -e "\t-d First data name [待处理的第一个文件名]"
    echo -e "\t-c Event display config file"
    echo -e "\t-j JSON export directory"
    echo -e "\t-m Link mapping file"
    echo -e "\t-a Channel mapping file"
    echo -e "\t-z Z position mapping file"
    echo -e "\t-n Noise file path [噪声文件路径]"
    echo -e "\t-t Threshold limit in baseline sigma"
    echo -e "\t-l Loop number (default 1) [处理的文件个数]"
    echo -e "\t-L Link used in hex value 1 stands for used and 0 for not used\r\n\t\t(default 0xFF,即8个通道都分析) \r\n\t [使用的link，16进制，1表示使用，0表示不使用]"
    echo -e "\t-N Proess pedestal raw data"
    echo -e "\t-D Skip USB data seperate [跳过USB数据解包]"
    echo -e "\t-F Skip FEC data decode [跳过FEC数据解码]"
    echo -e "\t-P Skip position decoding [跳过位置解码]"
    echo -e "\t-H Skip hit reconstruction"
    echo -e "\t-T Skip track seek and json export"
    echo -e "\t-V Skip confirm [跳过确认]"
    echo -e "\t-S Set base directory of the algorithms"
    echo -e "\t-h Help [帮助]"
    echo -e '\e[1;m '
    exit 1 # Exit script after printing help
}

get_script_dir () {
     SOURCE="${BASH_SOURCE[0]}"
     # While $SOURCE is a symlink, resolve it
     while [ -h "$SOURCE" ]; do
          DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
          SOURCE="$( readlink "$SOURCE" )"
          # If $SOURCE was a relative symlink (so no "/" as prefix, need to resolve it relative to the symlink base directory
          [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
     done
     DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
     echo "$DIR"
}

# [todo] better solution needed
source ~/software/root/bin/thisroot.sh

# Split current path with word "source"
BASE_PATH=$(dirname $(get_script_dir))

LOOP_NUM=1
LINK_NUM=0xFF
CALC_NOISE=0
THRESH_LIMIT=3
SKIP_USB_DATA_SEPERATE=0
SKIP_FEC_DATA_DEC=0
SKIP_POSI_DEC=0
SKIP_HIT_REC=0
SKIP_TRACK_SEEK=0
IS_VERBOSE=0
while getopts "c:j:m:a:z:d:n:t:l:L:S:NDFPHTV" opt
do
    case "$opt" in
        c ) EVE_CONFIG_FILE="$OPTARG" ;;
        j ) JSON_PATH="$OPTARG" ;;
        m ) LINK_MAPPING_FILE="$OPTARG" ;;
        a ) CHANNEL_MAPPING_FILE="$OPTARG" ;;
        z ) Z_POSITION_FILE="$OPTARG" ;;
        d ) MUSTC_DATA="$OPTARG" ;;
        n ) NOISE_FILE_PATH="$OPTARG" ;;
        t ) THRESH_LIMIT="$OPTARG" ;;
        l ) LOOP_NUM="$OPTARG" ;;
        L ) LINK_NUM="$OPTARG" ;;
        N ) CALC_NOISE=1 ;;
        D ) SKIP_USB_DATA_SEPERATE=1 ;;
        F ) SKIP_FEC_DATA_DEC=1 ;;
        P ) SKIP_POSI_DEC=1 ;;
        H ) SKIP_HIT_REC=1 ;;
        T ) SKIP_TRACK_SEEK=1 ;;
        V ) IS_VERBOSE=1 ;;
        S ) BASE_PATH="$OPTARG" ;;
        ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
    esac
done

# Print helpFunction in case parameters are empty
if [ -z "$MUSTC_DATA" ]
then
    echo "Data path is empty";
    helpFunction
    exit 1
fi

if [ -z "$NOISE_FILE_PATH" ]
then
   NOISE_FILE_PATH="${MUSTC_DATA%/*}/pedestal"
fi

if [ -z "$JSON_PATH" ]
then
    JSON_PATH="${MUSTC_DATA%/*}/json"
fi

if ! [[ "$LOOP_NUM" =~ ^-?[0-9]+$ ]]
then
    echo "Loop number must be an integer"
    helpFunction
    exit 1
fi

if echo "$LINK_NUM" | grep -q "0x"; then
    LINK_NUM="$LINK_NUM"
else
    LINK_NUM="0x$LINK_NUM"
fi


# Begin script in case all parameters are correct
if ! [ -a $MUSTC_DATA ]
then
    echo "File not found";
fi

LINK_CNT=0
for i in $(seq 8)
do
    a=$(($(($((LINK_NUM))>>$((i-1))))&0x1))
    if [ $a -eq 1 ]
    then
        LINK_CNT=$(($LINK_CNT+1))
    fi
done

if [ "$CALC_NOISE" = 1 ]
then
   SKIP_POSI_DEC=1
   SKIP_HIT_REC=1
   SKIP_TRACK_SEEK=1
   echo "Noise data run, position_decode, hit_recon and track_seek skipped"
fi

DATA_PREFIX=${MUSTC_DATA%-*}
DATA_SUFFIX=${MUSTC_DATA#*-}
START_LOOP_NUM=${DATA_SUFFIX%.dat}
LAST_LOOP_NUM=$(($START_LOOP_NUM+$LOOP_NUM))

echo "++++++"
echo "Current path is: $current_path"
echo "Algorithm base path to $BASE_PATH"
echo "Noise data path to $NOISE_FILE_PATH"

echo ""
echo "=== Info ==="
echo "First data path is $MUSTC_DATA"
echo "Data prefix is $DATA_PREFIX"
echo "Data suffix is $DATA_SUFFIX"
echo "Link Mask is $LINK_NUM"
echo "Link count is $LINK_CNT"
echo "Loop number is $LOOP_NUM"
echo "Start at loop $START_LOOP_NUM"
echo "Stop at loop $LAST_LOOP_NUM"

if [ "$VERBOSE" = 1 ]
then
   echo "Verbose mode is on";
   # Wait the user to press y or enter for continue and n for exit
   read -p "Continue? [y/n]" -n 1 -r
   echo    # (optional) move to a new line
   if [[ ! $REPLY =~ ^[Yy]$ ]]
   then
       echo "Exit"
       exit 1
   fi
   # read -p "Press enter to continue"
fi

echo ""
echo "--- Begin of processing"
### step 1
if [ "$SKIP_USB_DATA_SEPERATE" = 1 ]
then
    echo "Skip USB data seperate";
else
    echo "USB data seperate ...";
    USB_DATA_PROCESS="$BASE_PATH/bin/usb_data_separate"
    for ((i=$START_LOOP_NUM; i<$LAST_LOOP_NUM; i=i+1))
    do
      $USB_DATA_PROCESS -f "$DATA_PREFIX-${i}.dat" -r 1>/dev/null
    done
    echo -e '\e[1;42m USB data seperate done \e[1;m'
fi

### step 2
NEW_FILE_PATH="${MUSTC_DATA%/*}/dec_out"
FILE_NAME="${MUSTC_DATA##*/}"
FILE_NAME1=${FILE_NAME%-*}
if [ "$SKIP_FEC_DATA_DEC" = 1 ]
then
    echo "Skip FEC data dec";
else
    echo "FEC data decode ...";
    UNPACK="$BASE_PATH/bin/adas_data_unpack"
    for ((i=$START_LOOP_NUM; i<$LAST_LOOP_NUM; i=i+1))
    do
        for j in $(seq 8)
        do
            a=$(($(($((LINK_NUM))>>$((j-1))))&0x1))
            if [ $a -eq 0 ]
            then
                continue
            fi
            if [ "$CALC_NOISE" = 1 ]
            then
                $UNPACK -b -n $THRESH_LIMIT -f "$NEW_FILE_PATH/$FILE_NAME1-${i}_mt-$((${j}-1)).dat" 1>/dev/null

                # cp the pedestal parameters to default directory
                mkdir -p "${MUSTC_DATA%/*}/pedestal"
                cp "$NEW_FILE_PATH/unpack_result/$FILE_NAME1-${i}_mt-$((${j}-1))_base.txt" "${MUSTC_DATA%/*}/pedestal/mean_$((${j}-1)).txt"
                cp "$NEW_FILE_PATH/unpack_result/$FILE_NAME1-${i}_mt-$((${j}-1))_rms.txt" "${MUSTC_DATA%/*}/pedestal/rms_$((${j}-1)).txt"
                # cp the threshold parameters to default directory
                mkdir -p "${MUSTC_DATA%/*}/threshold"
                cp "$NEW_FILE_PATH/unpack_result/threshold_link-$((${j}-1))_bin.txt" "${MUSTC_DATA%/*}/threshold/"
            else
                $UNPACK -f "$NEW_FILE_PATH/$FILE_NAME1-${i}_mt-$((${j}-1)).dat" 1>/dev/null
            fi
        done
    done
    echo -e '\e[1;42m unpack data done\e[1;m'
fi

### step 3
NEW_FILE_PATH="${MUSTC_DATA%/*}/dec_out/unpack_result"
FILE_NAME="${MUSTC_DATA##*/}"
FILE_NAME1=${FILE_NAME%-*}
if [ "$SKIP_POSI_DEC" = 1 ]
then
    echo "Skip position decode";
else
    echo "Position decode ...";
    DECODE="$BASE_PATH/bin/adas_data_dec"
    if [ -z "$CHANNEL_MAPPING_FILE" ]
    then
        echo "channel_mapping param file is missing";
        helpFunction
        exit 1
    fi
    for ((i=$START_LOOP_NUM; i<$LAST_LOOP_NUM; i=i+1)); do
        for j in $(seq 8); do
            a=$(($(($((LINK_NUM))>>$((j-1))))&0x1))
            if [ $a -eq 0 ]; then
                continue;
            fi
            $DECODE -a -b "$NOISE_FILE_PATH/mean_$((j-1)).txt" -n "$NOISE_FILE_PATH/rms_$((j-1)).txt" -e "$BASE_PATH/share/param/$CHANNEL_MAPPING_FILE" -f "$NEW_FILE_PATH/$FILE_NAME1-${i}_mt-$(($j-1)).root" 1>/dev/null
        done
    done
    echo -e '\e[1;42m decode data done\e[1;m'
fi

### step 4
NEW_FILE_PATH="${MUSTC_DATA%/*}/dec_out/unpack_result/dec_result"
FILE_NAME="${MUSTC_DATA##*/}"
FILE_NAME1=${FILE_NAME%-*}
if [ "$SKIP_HIT_REC" = 1 ]; then
    echo "Skip hit position reconstruct";
else
    echo "Hit position reconstruct ...";
    HIT_POSI="$BASE_PATH/bin/hit_position_reconstruct"
    if [ -z "$Z_POSITION_FILE" ]
    then
        echo "z_position param file is missing";
        helpFunction
        exit 1
    fi
    if [ -z "$LINK_MAPPING_FILE" ]
    then
        echo "link_mapping param file is missing";
        helpFunction
        exit 1
    fi
    for ((i=$START_LOOP_NUM; i<$LAST_LOOP_NUM; i=i+1)); do
        for j in $(seq 8); do
            a=$(($(($((LINK_NUM))>>$((j-1))))&0x1))
            if [ $a -eq 0 ]; then
                continue;
            fi
            $HIT_POSI -p "$BASE_PATH/share/param/$LINK_MAPPING_FILE" -z "$BASE_PATH/share/param/$Z_POSITION_FILE" -L "$LINK_NUM" -l "$LINK_CNT" -V -f "$NEW_FILE_PATH/$FILE_NAME1-${i}_dec_mt-$((${j}-1)).root" 1>/dev/null
	    break
        done
    done
    echo -e '\e[1;42m hit_position_reconstrcut done\e[1;m'
fi

### step 5
NEW_FILE_PATH="${MUSTC_DATA%/*}/dec_out/unpack_result/dec_result"
FILE_NAME="${MUSTC_DATA##*/}"
FILE_NAME1=${FILE_NAME%-*}
if [ "$SKIP_TRACK_SEEK" = 1 ]; then
  echo "Skip track seek";
else
    echo "Track seek ...";
    mkdir -p "$JSON_PATH"
    TRACK_SEEK="$BASE_PATH/bin/track_seek"
    if [ -z "$EVE_CONFIG_FILE" ]
    then
        echo "system config file for event display is missing";
        helpFunction
        exit 1
    else
        cp "$BASE_PATH/share/param/$EVE_CONFIG_FILE" "$JSON_PATH/system.json"
    fi
    LAYER_MASK=$(($((1<<$LINK_CNT))-1))
    LAYER_MASK=$(printf "0x%X" $LAYER_MASK)
    for ((i=$START_LOOP_NUM; i<$LAST_LOOP_NUM; i=i+1)); do
        $TRACK_SEEK -j -A ${JSON_PATH} -f "$NEW_FILE_PATH/${FILE_NAME1}-${i}_dec_mt_hit_data_link"$LINK_NUM".root" -L $((LINK_CNT-1)) -D "$LINK_CNT" -l "$LAYER_MASK" 1>/dev/null
    done
    echo -e '\e[1;42m track_seek done\e[1;m'
fi

echo "--- End of processing"
